package practica4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class EchoClient extends Thread{

	private Socket sc;
	private BufferedReader in;
	private PrintWriter out;
	private BufferedReader keyboard;

	public static void main(String[] args) {
		String host = "localhost";
		int port = 1234;
		try{
			if(args.length >= 1) host = args[0];
			if(args.length >= 2) port = Integer.parseInt(args[1]);
		}catch (NumberFormatException e) {
			System.err.println("Port incorrecte. Utilitzant port per defecte: "+port);
		}
		new EchoClient(host,port).start();
	}

	public EchoClient(String host,int port){
		try {
			sc = new Socket(host,port);
			in = new BufferedReader(new InputStreamReader(sc.getInputStream()));
			out = new PrintWriter(sc.getOutputStream(),true);
			keyboard = new BufferedReader(new InputStreamReader(System.in));
		} catch (UnknownHostException e) {
			System.err.println("No s'ha trobat el host.");
			System.exit(-1);
		} catch (IOException e) {
			System.err.println("Error de tipus IO en crear el socket: "+e.getMessage());
			System.exit(-1);
		}
	}

	public void run(){
		while(true){
			try {
				String t = keyboard.readLine();
				out.println(t);
				String r = in.readLine();
				System.out.println(r);
				if(r.equalsIgnoreCase("END")) break;

			} catch (IOException e) {
				System.err.println("Error de tipus IO: "+e.getMessage());
			}
		}
		try {
			sc.close(); out.close(); in.close(); keyboard.close();
		} catch (IOException e) {
			System.err.println("Error de tipus IO en tancar el socket: "+e.getMessage());
		}
	}
}
